package cn.ghf.pay.service.impl;

import cn.ghf.basic.constant.PayBillBusinessType;
import cn.ghf.basic.exception.MyException;
import cn.ghf.basic.service.impl.BaseServiceImpl;
import cn.ghf.order.service.IProductOrderService;
import cn.ghf.pay.domain.AlipayInfo;
import cn.ghf.pay.domain.PayBill;
import cn.ghf.pay.mapper.AlipayInfoMapper;
import cn.ghf.pay.mapper.PayBillMapper;
import cn.ghf.pay.service.IPayBillService;
import cn.ghf.pay.utils.AlipayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class PayBillServiceImpl extends BaseServiceImpl<PayBill> implements IPayBillService {

    @Autowired
    private AlipayInfoMapper alipayInfoMapper;

    @Autowired
    private PayBillMapper payBillMapper;

    @Autowired
    private IProductOrderService productOrderService;

    @Override
    public String payRequest(PayBill payBill) {
        //校验
        if(payBill==null){
            throw new MyException("支付单不存在1");
        }
        PayBill payBill1 = payBillMapper.loadByUnionPaySn(payBill.getUnionPaySn());
        if(payBill1==null){
            throw new MyException("支付单不存在2");
        }
        //判断订单类型
        if("business_type_adopt".equals(payBill.getBusinessType())){
            //根据支付类型完成支付
            Long payChannel = payBill.getPayChannel(); ////0 余额 1 支付宝 2 微信 3 银联
            switch(payChannel.intValue()){

                case 1 :
                    //支付宝
                    AlipayInfo info = alipayInfoMapper.loadByShopId(payBill.getShop_id());
                    String pay = AlipayUtils.pay(info, payBill);
                    return pay;
                //微信
                case 2 :
                    //@TODO
                    break;
                //银联
                case 3 :
                    //@TODO
                    break;
                //余额
                default :
                    //@TODO
            }
        }else if(PayBillBusinessType.BUSINESS_TYPE_PRODUCT.equals(payBill.getBusinessType())){//服务类型
            Long payChannel = payBill.getPayChannel(); ////0 余额 1 支付宝 2 微信 3 银联
            switch(payChannel.intValue()){

                case 1 :
                    //支付宝
                    AlipayInfo info = alipayInfoMapper.loadByShopId(payBill.getShop_id());
                    String pay = AlipayUtils.pay(info, payBill);
                    return pay;
                //微信
                case 2 :
                    //@TODO
                    break;
                //银联
                case 3 :
                    //@TODO
                    break;
                //余额
                default :
                    //@TODO
            }
        }

        return null;
    }

    @Override
    public PayBill queryByUnionPaySn(String unionPaySn) {
        return payBillMapper.loadByUnionPaySn(unionPaySn);
    }
}
